﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.Utility;

namespace FileManager_Client.PresentationLayer
{
    public partial class AddFile : Form
    {
        private UserLoginResult userSession;
        private List<string> _hasFolderNameCollection;
        private string _parentFolderId;
        private ToolTip _fileNameToolTip = new ToolTip();
        private FileService fileService;
        private WaitDialogForm _waitBeforeLogin;
        private ServerFiles _serverFiles;
        private static object lockWait = new object();
        public AddFile(List<string> hasFolderNameCollection, string parentFolderId, ServerFiles serverFiles)
        {
            InitializeComponent();
            _hasFolderNameCollection = hasFolderNameCollection;
            userSession = CacheGlobal.GetCache(GlobalString.System_Config_String.UserSession) as UserLoginResult;
            fileService = new FileService();
            _parentFolderId = parentFolderId;
            _serverFiles = serverFiles;
            _fileNameToolTip.AutoPopDelay = 5000;
            _fileNameToolTip.InitialDelay = 1000;
            _fileNameToolTip.ReshowDelay = 500;
            _fileNameToolTip.ShowAlways = true;
            _fileNameToolTip.IsBalloon = true;
            _fileNameToolTip.ToolTipIcon = ToolTipIcon.Error;
            _fileNameToolTip.Active = true;
            _fileNameToolTip.ToolTipTitle = "输入提示:";
            txtFileName.TextChanged += txtFileName_TextChanged;
            txtFileName.KeyPress += txtFileName_KeyPress;
        }

        void txtFileName_KeyPress(object sender, KeyPressEventArgs e)
        {
                if (e.KeyChar != 13) return;
                if (CheckFolderName())
                    CreateNewFolder();
        }

        void txtFileName_TextChanged(object sender, EventArgs e)
        {
            _fileNameToolTip.Hide(txtFileName);
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void BtnConfirm_Click(object sender, EventArgs e)
        {
            if (CheckFolderName())
                CreateNewFolder();
        }

        private void CreateNewFolder()
        {
            try
            {
                lock (lockWait)
                {
                    _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.FileReNameStr,
                                                          GlobalString.System_Config_String.MbxInfoStr)
                    {
                        BackColor = BackColor
                    };
                    _waitBeforeLogin.Hide();
                }
                var backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += backgroundWorker_DoWork;
                var newFolderArgs = new NewFolderArgs
                                        {
                                            NewFolderNamek__BackingField = txtFileName.Text,
                                            ParentFolderSidk__BackingField = _parentFolderId,
                                            UserIdk__BackingField = userSession.UserIdk__BackingField
                                        };
                backgroundWorker.RunWorkerAsync(newFolderArgs);
                _waitBeforeLogin.ShowDialog();
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CreateNewFolder has problem", ex);
                XtraMessageBox.Show("创建文件夹失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
            }
        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var newFolderArgs = e.Argument as NewFolderArgs;
                var reslut = fileService.CreateFolder(newFolderArgs);
              
                if (reslut.Resultk__BackingField)
                {
                    Invoke((EventHandler)delegate
                    {
                        _waitBeforeLogin.Caption = "创建文件夹成功!";
                    });
                    var _userService = new UserService();
                    Invoke((EventHandler)delegate
                    {
                        _waitBeforeLogin.Caption = GlobalString.System_Config_String.CreateFolderLoadingFolderStr;
                    });
                    var folderCollectionResult = _userService.SyncGetFolderService();
                    CacheGlobal.Add(GlobalString.System_Config_String.FolderCollectionCache, folderCollectionResult.Result);
                     Invoke((EventHandler)delegate
                    {
                        _waitBeforeLogin.Caption = GlobalString.System_Config_String.CreateFolderLoadingFolderRoleStr;
                    });
                    var folderRoleCollectionResult = _userService.SyncGetFolderRoleService();
                    CacheGlobal.Add(GlobalString.System_Config_String.FolderRoleCollectionCache, folderRoleCollectionResult.Result);
                    Invoke((EventHandler)delegate
                    {
                        _waitBeforeLogin.Close();
                    });
                    Invoke((EventHandler)delegate
                    {
                        Close();
                    });
                }
                else
                {
                    var message = string.Empty;
                    switch (reslut.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.CreateFolderException:
                            message = GlobalString.System_Exception_String.CreateFolderException;
                            break;
                        case BaseExceptionEnum.CreateFolderHaveFolderExpcetion:
                            message = GlobalString.System_Exception_String.CreateFolderHaveFolderExpcetion;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CreateNewFolder backgroundWorker_DoWork has problem", ex);
                XtraMessageBox.Show("修改文件名失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                Invoke((EventHandler)delegate
                {
                    Close();
                });
            }
        }

        private bool CheckFolderName()
        {
            var folderName = txtFileName.Text;
            if (folderName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
            {
                _fileNameToolTip.Show(string.Empty, txtFileName, 0);
                _fileNameToolTip.Show("文件夹名称不能包含\\/:*?\"<>| 特殊字符!", txtFileName, 0);
                return false;
            }
            if (string.IsNullOrEmpty(folderName.Trim()))
            {
                _fileNameToolTip.Show(string.Empty, txtFileName, 0);
                _fileNameToolTip.Show("文件名不能为空!", txtFileName, 0);
                return false;
            }
            if (_hasFolderNameCollection.Contains(folderName))
            {
                _fileNameToolTip.Show(string.Empty, txtFileName, 0);
                _fileNameToolTip.Show("该文件夹中已经包含了这个名称!", txtFileName, 0);
                return false;
            }
            return true;
        }
    }
}
